package model;

import java.util.StringTokenizer;

import net.sf.vcard4j.java.type.TEL;

public class PhoneNumberWrapper {
	
	private TEL number;
	
	private String countryCode;
	private String areaCode;
	private String numberCode;
	
	public PhoneNumberWrapper(TEL phoneNumber) {
		this.number = phoneNumber;
		countryCode = null;
		areaCode = null;
		numberCode = null;
	}
	
	public PhoneNumberWrapper() {}
	
	private void splitNumber() {
		String myNumber = this.number.get();
		
		boolean foundPlus = false;
		if(myNumber.indexOf("+") != -1) foundPlus = true;
		
		myNumber = myNumber.replace('+', ' ');
		myNumber = myNumber.trim();
		StringTokenizer tokenizer = new StringTokenizer(myNumber, "-", true);
		
		if(foundPlus) {			// if no country code given (no +xy existing, skip)
			// country code
			if(tokenizer.hasMoreTokens()) {
				String token = tokenizer.nextToken().trim();
				if(token.compareTo("-") != 0) {
					countryCode = token;
					if(tokenizer.hasMoreTokens()) tokenizer.nextToken();
				}
			}
		}
		// area code
		if(tokenizer.hasMoreTokens()) {
			String token = tokenizer.nextToken().trim();
			if(token.compareTo("-") != 0) {
				areaCode = token;
				if(tokenizer.hasMoreTokens()) tokenizer.nextToken();
			}
		}
		// number code
		if(tokenizer.hasMoreTokens()) {
			String token = tokenizer.nextToken().trim();
			numberCode = token;
		}
		
	}
	
	private void setNumber() {
		String myNumber = "+" + countryCode + "-" + areaCode + "-" + numberCode;
		this.number.set(myNumber);
	}
	
	public boolean existsCountryCode() {
		if(getCountryCode() == null || getCountryCode().trim().length() == 0) return false;
		return true;
	}
	
	public String getCountryCode() {
		splitNumber();
		return countryCode;
	}
	
	public void setCountryCode(String code) {
		splitNumber();
		countryCode = code;
		setNumber();
	}
	
	public boolean existsAreaCode() {
		if(getAreaCode() == null || getAreaCode().trim().length() == 0) return false;
		return true;
	}
	
	public String getAreaCode() {
		splitNumber();
		return areaCode;
	}
	
	public void setAreaCode(String code) {
		splitNumber();
		areaCode = code;
		setNumber();
	}
	
	public boolean existsNumberCode() {
		if(getNumberCode() == null || getNumberCode().trim().length() == 0) return false;
		return true;
	}
	
	public String getNumberCode() {
		splitNumber();
		return numberCode;
	}
	
	public void setNumberCode(String code) {
		splitNumber();
		numberCode = code;
		setNumber();
	}
	
	public String print() {
		if(number == null || number.get() == null || number.get().trim().length() == 0) return "";
		return number.get();
	}
	
}